package no.gnet.edvd.feed;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import no.gnet.edvd.feed.types.RemoteMatch;
import no.gnet.edvd.types.Category;
import no.gnet.edvd.types.MatchEvent;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import com.google.gson.stream.JsonReader;

public class FeedReader {

	private static Logger logger = Logger.getLogger(FeedReader.class);

	public void read(InputStream feed) {

	}

	public Map<RemoteMatch, MatchEvent> readMatchesFromStream(
			InputStream fileInputStream) throws IOException {

		List<RemoteMatch> matches = null;
		try {
			matches = readJsonStream(fileInputStream);
		} catch (NoMatchesException e) {
			logger.warn("No matches");
		}
		Map<RemoteMatch, MatchEvent> mevents = new HashMap<RemoteMatch, MatchEvent>();
		if (matches != null) {
			readTheMatches(matches, mevents);
		}
		return mevents;
	}

	private void readTheMatches(List<RemoteMatch> matches,
			Map<RemoteMatch, MatchEvent> mevents) {
		for (Iterator<RemoteMatch> iterator = matches.iterator(); iterator
				.hasNext();) {
			RemoteMatch remoteMatch = (RemoteMatch) iterator.next();
			String away = remoteMatch.match_visitorteam_name;
			String home = remoteMatch.match_localteam_name;
			MatchEvent mevent = new MatchEvent(home, away);
			mevent.category = Category.SPORTS;
			
			String match_formatted_date = remoteMatch.match_formatted_date;
			mevent.description = "Match between " + home + " and " + away
					+ ", " + match_formatted_date;
			mevent.setLeague(remoteMatch.match_comp_id);
			mevent.name = home + "-" + away;
			
			String match_time = remoteMatch.match_time;
			DateTime matchtime = fetchMatchTime(match_time, match_formatted_date);
//			System.out.println(match_time+":"+ match_formatted_date+" gives " + new Timestamp(matchtime.getMillis()));
			mevent.eventDecidedTime = matchtime;
			mevent.betDeadline = matchtime;
			mevent.eventPosted = new DateTime();

			mevents.put(remoteMatch, mevent);
		}
	}

	private DateTime fetchMatchTime(String mtime, String mdate) {
		DateTime dt = DateTimeFormat
			    .forPattern("dd.MM.yyyy HH:mm").parseDateTime(mdate+" "+ mtime);
		DateTime dtLondonSameTime = dt.withZoneRetainFields(DateTimeZone.forID("UTC"));
		return dtLondonSameTime;
}

	public List<RemoteMatch> readJsonStream(InputStream in) throws IOException,
			NoMatchesException {
		JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
		String version;
		String aPIRequestsRemaining;
		String developerAuthentication;
		try {
			reader.beginObject();
			while (reader.hasNext()) {
				if (reader.peek().equals("matches")) {
					break;
				}
				String name = reader.nextName();
				if (name.equals("APIVersion")) {
					version = reader.nextString();
				} else if (name.equals("APIRequestsRemaining")) {
					aPIRequestsRemaining = reader.nextString();
				} else if (name.equals("DeveloperAuthentication")) {
					developerAuthentication = reader.nextString();
				} else {
					break;
				}
			}

			return readMessagesArray(reader);
		} finally {
			reader.close();
		}
	}

	private List<RemoteMatch> readMessagesArray(JsonReader reader)
			throws IOException, NoMatchesException {
		List<RemoteMatch> matches = new ArrayList<RemoteMatch>();

		String name = reader.peek().name();
		if (!"BEGIN_ARRAY".equals(name)) {
			// no matches
			throw new NoMatchesException("No matches");
		}
		reader.beginArray();
		while (reader.hasNext()) {
			matches.add(readMatch(reader));
		}
		reader.endArray();
		return matches;
	}

	private RemoteMatch readMatch(JsonReader reader) throws IOException {
		RemoteMatch remoteMatch = new RemoteMatch();
		reader.beginObject();
		while (reader.hasNext()) {
			String name = reader.nextName();
			if (name.equals("match_id")) {
				remoteMatch.match_id = reader.nextLong();
			} else if (name.equals("match_static_id")) {
				remoteMatch.match_static_id = reader.nextLong();
			} else if (name.equals("match_localteam_name")) {
				remoteMatch.match_localteam_name = reader.nextString();
			} else if (name.equals("match_localteam_id")) {
				remoteMatch.match_localteam_id = reader.nextLong();
			} else if (name.equals("match_visitorteam_name")) {
				remoteMatch.match_visitorteam_name = reader.nextString();
			} else if (name.equals("match_visitorteam_id")) {
				remoteMatch.match_visitorteam_id = reader.nextLong();
			} else if (name.equals("match_formatted_date")) {
				remoteMatch.match_formatted_date = reader.nextString();
			} else if (name.equals("match_time")) {
				remoteMatch.match_time = reader.nextString();
			} else if (name.equals("match_comp_id")) {
				remoteMatch.match_comp_id = reader.nextString();
			} else if (name.equals("match_ft_score")) {
				remoteMatch.match_ft_score = reader.nextString();
			} else {
				reader.skipValue();
			}
		}
		reader.endObject();
		return remoteMatch;

	}

}
